package com.kylin.common.security.exception;

import com.kylin.common.core.beans.GlobalResultCode;
import com.kylin.common.core.beans.ResultBean;
import org.springframework.core.annotation.Order;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.Serializable;

/**
 * 全局异常处理器
 * 为什么会有这个类：@PreAuthorize 注解的异常，抛出AccessDeniedException异常，不会被accessDeniedHandler捕获，而是会被全局异常捕获。
 * https://blog.csdn.net/shan165310175/article/details/105415249/
 * @author wuhao
 * @version 1.0 - 2023/1/10
 */
@RestControllerAdvice
//需要比la-common-core中的拦截要优先拦截
@Order(-1)
public class GlobalExceptionHandler {

    /**
     * 权限不足异常
     * @return
     * @author wuhao
     */
    @ExceptionHandler(AccessDeniedException.class)
    public ResultBean<Serializable> handleAccessDeniedException(AccessDeniedException e) {
        return new ResultBean<>(GlobalResultCode.FORBIDDEN);
    }

    /**
     * 验证码校验失败
     * @return
     * @author wuhao
     */
    @ExceptionHandler(CaptchaException.class)
    public ResultBean<Serializable> handleCaptchaException(CaptchaException e) {
        return new ResultBean<>(GlobalResultCode.UNAUTHORIZED.getCode(), e.getMessage());
    }
}
